package id.co.shuba.spamobile.task;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.data.BaseDB;
import id.co.shuba.spamobile.data.DDLDB;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.util.Base64;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;

public class SyncTableTask extends AsyncTask<String, Integer, AsyncTaskResult<Void>> {	
	DatabaseHandler _db;
	ProgressDialog _dialog;
	WebServiceHelper _ws;	
	
	private OnDownloadCompleteListener _callback;
	
	public void setOnCheckingFinished(OnDownloadCompleteListener callback) {
		_callback = callback;
	}	
	
	public SyncTableTask(DatabaseHandler db, WebServiceHelper ws, ProgressDialog dialog) {
		_ws = ws;		
		_dialog = dialog;					
	}	
	
	public void setDialog(ProgressDialog dialog) {
		_dialog = dialog;
		if (getStatus() == Status.RUNNING)
			_dialog.show();
	}
	
	@Override
	protected void onPreExecute() {	
		super.onPreExecute();	
		_dialog.show();
	}
	
	@Override
	protected AsyncTaskResult<Void> doInBackground(String... params) {
		try {			
			Map<String, Object> properties = new HashMap<String, Object>();				
			properties.put("date", App.getProcessDateTime());
			String result = _ws.Call("GetUpdateTable", properties).toString();						
			String strJSON = new String(Base64.decode(result, Base64.GZIP)); 					
			
			JSONObject res = new JSONObject(strJSON);
			String error = res.getString("error");
			if (error.length() > 0 && !error.equals("null"))
				throw new Exception(error);
				
			JSONArray jsonArray = res.getJSONArray("result");										
			DDLDB ddl = new DDLDB(_db);
						
			int length = jsonArray.length();						
			for (int i = 0; i < length; i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String tableName = jsonObject.getString("tableName");
				String fieldName = jsonObject.getString("fieldName");
				String dataType = jsonObject.getString("dataType");
				String isTableNew = jsonObject.getString("isTableNew");					
				
				boolean columnExists = ddl.isColumnExists(tableName, fieldName);
				
				try {
					if (!columnExists && "0".equals(isTableNew))
						ddl.alterColumn(tableName, fieldName, dataType);
					if ("1".equals(isTableNew))
					ddl.createTable(dataType);
				} catch (Exception e) {
					//ignore aje, next ke column berikutnya
					Log.e("Create Table", "Error when creating table --> " + e.getMessage());
				}					
			}
			
			return new AsyncTaskResult<Void>((Void)null);
		} catch (Exception e) {			
			return new AsyncTaskResult<Void>(e);
		}			
	}
	
	@Override
	protected void onPostExecute(AsyncTaskResult<Void> result) {	
		_dialog.dismiss();
		
		if (_callback != null)
			_callback.onDownloadComplete(result.getError());
	}	
		
}